package com.bus

import org.groovyflow.db.*
import org.groovyflow.util.*

class Product extends ActiveRecord{
	
	public String gTableName(){
		return "productx"
	}

	def changePrice(priceChange){
		println 'Entering changePrice'
		DbHelp.inTrx({
			priceChange.oldPrice = this.price
			this.price = addToPriceWhatIf(priceChange.increase)
			this.save()
			priceChange.productId = this.id 
			priceChange.save()
		})
	}
	
	
	def findWithCategoryInfo(id){
		findBySql("""select ${gTableName()}.*, category.name as categoryname from 
				     ${gTableName()}, category where ${gTableName()}.categoryid = category.id 
				     and ${gTableName()}.id = ? """, 
				     [id])[0]
	}

	//Checks that toAdd is in a valid format.  For example, 0.357 would cause an exception.
	//It's the job of validations to make sure an exception doesn't get thrown.
	def addToPriceWhatIf(toAdd){
		Money original = new Money(price.toString())
	    Money toAddM = new Money(toAdd.toString())
		Money newPrice = original.add(toAddM)
		return new BigDecimal(newPrice.toString())
	}

	def wouldBeNegative(toAdd){
		def newValue = addToPriceWhatIf(toAdd)
		return newValue < 0
	}

}